#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2024/9/5 11:17
# @Author  : weidma
import subprocess

import pandas as pd
import json


def export_results(all_black_frames, output_format='csv', output_file='black_frames_results'):
    '''
    导出报告
    :param black_frames:
    :param output_format:
    :param output_file:
    :return:
    '''
    # 将所有视频的黑屏帧信息汇总
    all_results = []
    for video_path, frames in all_black_frames.items():
        for frame_info in frames:
            all_results.append({'video': video_path, **frame_info})  # 添加视频路径和帧信息

    if output_format == 'csv':
        df = pd.DataFrame(all_results)  # 将结果转换为DataFrame
        df.to_csv(f'{output_file}.csv', index=False)  # 导出为CSV文件
        print(f"结果已导出为 {output_file}.csv")
    elif output_format == 'json':
        with open(f'{output_file}.json', 'w') as json_file:  # 打开JSON文件
            json.dump(all_results, json_file, indent=4)  # 导出为JSON文件
        print(f"结果已导出为 {output_file}.json")
    else:
        print("不支持的格式，请选择 'csv' 或 'json'")


def get_video_info(video_path):
    '''
    使用FFmpeg命令获取视频信息
    :param video_path:
    :return:
    '''
    command = [
        'ffmpeg',
        '-i', video_path,
        '-f', 'null',
        '/dev/null'  # 将输出重定向到null设备
    ]

    # 执行FFmpeg命令并捕获输出
    result = subprocess.run(command, stderr=subprocess.PIPE, universal_newlines=True)

    # 从输出中提取比特率
    bitrate = None
    for line in result.stderr.split('\n'):
        if 'bitrate:' in line:  # 查找包含比特率的行
            bitrate = line.split('bitrate:')[1].strip()  # 提取比特率
            break

    return bitrate  # 返回比特率
